package com.lr.server.demo3;

import java.io.IOException;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class WebAPP {
  
	private static ServletContext setvletContext;
	static{
		setvletContext = new ServletContext();
		
		Map<String,String> mapping = setvletContext.getMapping();
//		mapping.put("/login", "login");
//		mapping.put("/reg", "register");
		
		Map<String,String> servlet = setvletContext.getServlet();
//		servlet.put("login", "com.lr.server.demo3.LoginServlet");
//		servlet.put("register", "com.lr.server.demo3.RegisterServlet");
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser paser = factory.newSAXParser();
			ServletHandler handler = new ServletHandler();
			paser.parse(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("com/lr/server/demo3/web.xml"), handler);
			mapping = handler.getMapping();
			servlet = handler.getServlet();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static Servlet getSevlet(String url) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
		if(null == url || url.trim().equals("")){
			return null;
		}
		//return setvletContext.getServlet().get(setvletContext.getMapping().get(url));
		String name = setvletContext.getServlet().get(setvletContext.getMapping().get(url));
		Class clz = Class.forName(name);
		Servlet servlet = (Servlet) clz.newInstance();
		return servlet;
	}

}
